package com.dbflow5.observing;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Description:
 */
public abstract class OnTableChangedObserver {

    List<Class<?>> tables;

    public OnTableChangedObserver(List<Class<?>> tables){
        this.tables = tables;
    }

    /**
     * Called when a table or set of tables are invalidated in the DB.
     *
     * @param tables tables
     */
    protected abstract void onChanged(Set<Class<?>> tables);

    static class OnTableChangedObserverWithIds{

        OnTableChangedObserver observer;
        int[] tableIds;

        OnTableChangedObserverWithIds(OnTableChangedObserver observer, int[] tableIds){
            this.observer = observer;
            this.tableIds = tableIds;
        }

        private Set<Class<?>> singleTableSet(){
            if(tableIds.length == 1){
                Set<Class<?>> classSet = new HashSet<>();
                classSet.add(observer.tables.get(0));
                return classSet;
            }
            return null;
        }

        void notifyTables(boolean[] invalidationStatus) {
            Set<Class<?>> invalidatedTables = null;

            for(int index= 0;index<tableIds.length;index++){
                int tableId = tableIds[index];
                if (invalidationStatus[tableId]) {
                    Set<Class<?>> singleTableSet = singleTableSet();
                    if (singleTableSet != null) {
                        invalidatedTables = singleTableSet;
                    } else {
                        if (invalidatedTables == null) {
                            invalidatedTables = new HashSet<>();
                        }
                        invalidatedTables.add(observer.tables.get(index));
                    }
                }
            }
            observer.onChanged(invalidatedTables);
        }
    }
}

